/* @flow */

import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  SegmentedControlIOS,
  Image,
  Button,
  SectionList,
  ScrollView,
  RefreshControl,
  TouchableOpacity,
} from 'react-native';

import{
  TabNavigator,
  NavigationActions,
} from 'react-navigation';

var Dimensions = require('Dimensions');

var {width} = Dimensions.get('window');
var {height} = Dimensions.get('window');

var cols = 3;
var vmargin = 10;
var boxW = (width - ((cols+1)*vmargin)-20)/cols;
var boxH = 80;
var hMargin = 10;

let url;

export default class AppCommunity extends Component {

  static navigationOptions = ({navigation,screenProps}) => {
    return {
      header: <View></View>
    }
  }

  constructor(props){
  	super(props);
  	this.state = {
      selectedIndex:0,
      data:[],
      newData:[],
      essenceData:[],
      refreshing:false,
      newPage:0,
      essencePage:0,
    };
  }

  componentWillMount() {

    this.setState({
      refreshing:true,
    });

    this.requestData(this.state.selectedIndex)

  }

  requestData(selectedIndex){

    if (selectedIndex == 0) {

      url='http://yiapi.xinli001.com/fm/forum-thread-list.json?flag=0&size=10&key=c0d28ec0954084b4426223366293d190&offset='+this.state.essencePage+'&type='+'1'

      // this.setState({refreshing:true})

    }else {
      url='http://yiapi.xinli001.com/fm/forum-thread-list.json?flag=0&size=10&key=c0d28ec0954084b4426223366293d190&offset='+this.state.newPage+'&type='+'0'
    }

    let map = {

      method:'GET'//请求类型

    };

    map.follow = 20;//设置请求允许的最大重定向次数，0为不允许重定向
    map.timeout = 10;//设置超时时间，0为没有超时时间，这个值在重定向时会被重置

    fetch(url,map)
    .then((response)=>{
      // console.log(response);

      return response.json()//对接收到的HTTP回应消息体进行JSON解析

    })
    .then((responseData)=>{
      // 拿到json数据
      var jsonData = responseData.data;

      // console.log(jsonData);

      let cityInfos = [];//SectionList的数据源


      let section = {}

      section.key = 1;//每段加一个key
      // section.key = 1;//每段加一个key
      // section.data = jsonData;



      // section.data =(selectedIndex==0?this.state.essenceData[0].data:this.state.newPage[0].dat).concat(jsonData);

      // console.log(section);

      // cityInfos[0] = section;

      if (selectedIndex==0) {

        if (this.state.essenceData.length==0) {

          section.data = jsonData;

          cityInfos[0] = section;

        }else {

          section.data = this.state.essenceData[0].data.concat(jsonData);

          cityInfos[0] = section;

        }

        console.log(cityInfos);

        this.setState({
          essenceData:cityInfos,
          essencePage:this.state.essencePage+=10,
          refreshing:false,
        })
      }else {

        if (this.state.newData.length==0) {

          section.data = jsonData;

          cityInfos[0] = section;

        }else {

          section.data = this.state.newData[0].data.concat(jsonData);

          cityInfos[0] = section;

        }

        console.log(cityInfos);

        this.setState({
          newData:cityInfos,
          newPage:this.state.newPage+=10,
          refreshing:false,
        })
      }

    })
    .catch((error)=>{
      console.log(error);
    })

  }

  render() {

    return (
      <View style={styles.container}>
        <View style={styles.headerViewStyle}>
          <View style={styles.headerTopViewStyle}>
            <TouchableOpacity activeOpacity ={0.5} onPress = {() =>{console.log('我到这里了');
              this.props.navigation.navigate('PostEditView',{name:'2-1'})}}>
              <Image
                source={require('../img/communityImg/PostEdit.png')}
                // source={require('../img/tabicon/shezhiXiong1.png')}
                style={styles.postEditImageStyle}>
              </Image>
            </TouchableOpacity>
            <SegmentedControlIOS
              values={['精华','最新']}
              style={styles.segmentStyle}
              tintColor="orange"
              selectedIndex={this.state.selectedIndex}
              onChange={this.onChange}
              >
            </SegmentedControlIOS>
            <TouchableOpacity activeOpacity ={0.5} onPress = {() =>{console.log('我到这里了');
              this.props.navigation.navigate('PlayingListView',{name:'2-1'})}}>
              <Image
                source={require('../img/communityImg/littlePlaying1.png')}
                style={styles.littlePlayingImageStyle}>
              </Image>
            </TouchableOpacity>
          </View>
          <View style={styles.lineStyle}>
          </View>
        </View>

        <SectionList
          // sections={this.state.data}
          sections={this.state.selectedIndex==0?this.state.essenceData:this.state.newData}
          renderItem={this.renderItem}
          renderSectionHeader={this.renderSectionHeader}//每段的段头
          ItemSeparatorComponent={this.itemSeparatorComponent}
          keyExtractor = {this.keyExtractor}
          stickySectionHeadersEnabled={false}
          // onEndReached={this.onEndReached}
          // onEndReachedThreshold ={0}
          // onRefresh = {this.onRefresh}
          // refreshing = {this.state.refreshing}
          refreshControl={
          <RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={this.onRefresh}
            tintColor="gray"
            title="正在刷新...."
            titleColor="gray"
            progressBackgroundColor="#ffff00"
          />}
          >
        </SectionList>
      </View>
    );
  }

  renderItem = (item) => {
    // console.log(item);
      return (
        <TouchableOpacity activeOpacity ={0.5} onPress = {()=>{
          this.props.navigation.navigate('DetailsView',{itemID:item.item.id})
          // console.log(item);
        }}>
          <View style={{backgroundColor:'white'}}>
            <View style={styles.itemTopView}>
              <Image
                style={styles.itemImageViewStyle}
                source={{uri:item.item.user.avatar}}>
              </Image>

              <View style={styles.titleViewStyle}>
                <Text style={styles.nameTextStyle}>
                  {item.item.user.nickname}
                </Text>
                <Text style={styles.updatedTextStyle}>
                  {item.item.updated}
                </Text>
              </View>

              <Text
                style={styles.numTextViewStyle}>
                {item.item.commentnum}
              </Text>

              <Image
                style={styles.commentPaoImageViewStyle}
                source={require('../img/communityImg/commentPao.png')}
                // source={{uri:item.item.user.avatar}}
                // source={{uri:'https://ws1.sinaimg.cn/large/006tNc79ly1ficcfl33d7j300u00o0sh.jpg'}}
                ></Image>
            </View>
            <Text
              style={styles.titleTextStyle}>
              {item.item.title}
            </Text>
            <Text
              style={styles.contentTextStyle}
              numberOfLines={3}
              >
              {item.item.content}
            </Text>

            <View style={styles.innerAllImageContentStyle}>
              {this.renderAllImages(item)}
            </View>
          </View>
        </TouchableOpacity>

      );
  }

  itemSeparatorComponent=()=>{
    return(
        <View style={styles.headerView}></View>
    );
  }

  renderSectionHeader = (section) => {
        return (
            <View style={styles.headerView}>

            </View>
        );
  }

  keyExtractor(item, index){

    return item.id.toString();

  }

  onEndReached=()=>{
    console.log('哈哈哈哈哈哈哈');
  }

  onChange=(event)=>{

    // console.log(event.nativeEvent.selectedSegmentIndex);

    this.setState({
      selectedIndex:event.nativeEvent.selectedSegmentIndex,
    });

    // console.log(this.state.selectedIndex);
    if (event.nativeEvent.selectedSegmentIndex==0) {

      if (this.state.essenceData.length==0) {

        this.setState({
          refreshing:true,
        })

        this.requestData(event.nativeEvent.selectedSegmentIndex)

      }

    }else {

      if (this.state.newData.length==0) {

        this.setState({
          refreshing:true
        })

        this.requestData(event.nativeEvent.selectedSegmentIndex)

      }

    }

  }

  onRefresh = (e)=>{

    this.setState({
      refreshing:true,
    });

    this.requestData(this.state.selectedIndex);

  }

  gotoPostEditView = ()=>{
    const { navigate } = this.props.navigation;
  }

  renderAllImages =(item)=>{

    // console.log(item);

    var allImages = [];

    if (item.item.images.length>0) {

      var allContentImages = item.item.images;

      for(let i =0; i<item.item.images.length;i++){
        var imageContent = item.item.images[i];
        // console.log('pppppp'+imageContent);
        allImages.push(
        <View key ={i} style ={styles.innerImagesStyle}>
          <Image source ={{uri:imageContent}} style ={styles.imageContentStyle}/>
        </View>
        );


      }

    }



    return allImages;

}

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  headerViewStyle:{
    height:55,
    backgroundColor:'white',
  },
  segmentStyle:{
    width:160,
    marginTop:20,
    marginLeft:(width-160)/2-32,
  },
  lineStyle:{
    height:1,
    width:width,
    backgroundColor:'gray',
  },
  itemTopView:{
    // 改变主轴的方向
    flexDirection:'row',
    marginTop:10,
    width:width,
    // backgroundColor:'red'
  },
  itemImageViewStyle:{
    width:32,
    height:32,
    marginLeft:10,
  },
  commentPaoImageViewStyle:{
    width:15,
    height:12,
    marginLeft:5,
  },
  headerView:{
    height:15,
    backgroundColor:'lightgray'
  },
  titleViewStyle:{
    marginLeft:10,
  },
  nameTextStyle:{
    fontSize:13,
    color:'gray',
    marginTop:0,
    width:200,
  },
  updatedTextStyle:{
    fontSize:10,
    color:'lightgray',
    marginTop:4,
  },
  numTextViewStyle:{
    marginLeft:60,
    fontSize:10,
    width:30,
    color:'lightgray',
    textAlign:'right',
  },
  contentTextStyle:{
    color:'lightgray',
    fontSize:13,
    margin:8,
    lineHeight:20,
  },
  titleTextStyle:{
    color:'black',
    fontSize:15,
    marginTop:10,
    marginLeft:8,
  },
  headerTopViewStyle:{
    width:width,
    height:54,
    // 改变主轴的方向
    flexDirection:'row',
  },
  postEditImageStyle:{
    height:22,
    width:22,
    marginLeft:10,
    marginTop:23,
  },
  littlePlayingImageStyle:{
    height:18,
    width:17,
    marginLeft:(width-160)/2-30,
    marginTop:25,
  },
  innerImagesStyle:{
  width:boxW,
  height:boxW,
  marginLeft:vmargin,
  marginTop:hMargin,
  marginBottom:hMargin,
  backgroundColor:'blue',
  },
  imageContentStyle:{
    width:boxW,
    height:boxW,
  },
  innerAllImageContentStyle:{
    flexDirection:'row'
  }
});
